package com.tianji.learning.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationPlusRequest;
import com.aliyun.green20220302.models.TextModerationPlusResponse;
import com.aliyun.green20220302.models.TextModerationPlusResponseBody;
import com.tianji.learning.enums.TextModerationServiceType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class AliyunTextModerationHandler {
    @Autowired
    Client client;

    public String textModeration(String content, TextModerationServiceType type) {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);
        TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
        // 检测类型
        textModerationPlusRequest.setService(type.getValue());
        textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());
        TextModerationPlusResponse response = null;
        try {
            response = client.textModerationPlus(textModerationPlusRequest);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                Integer code = result.getCode();
                if (200 == code) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    log.info("阿里云文档检测服务响应结果：" + JSON.toJSONString(data, true));
                } else {
                    log.error("阿里云文档检测服务响应错误：text moderation not success. code:" + code);
                }
            } else {
                log.error("阿里云文档检测服务请求出错：response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response.getBody().getData() != null) {
            return response.getBody().getData().getResult().get(0).getLabel();
        }
        log.warn("阿里云文档检测服务失效!!!!");
        return null;
    }
}
